﻿using OfficeOpenXml;
using OfficeOpenXml.Drawing.Chart;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Forms; // 添加此引用来使用 System.Windows.Forms 命名空间
using MessageBox = System.Windows.MessageBox;  // 明确指定使用 System.Windows.MessageBox

namespace ZTZP_BEMSS_WPF
{
    // ExcelReader.Part2.cs
    public partial class ExcelReader
    {
        // 导出投标基准价的函数
        public static string ExportEvalBenchmarkPrice(ObservableCollection<BasePriceEntry> data)
        {
            // 选择保存路径和文件名
            string selectedFilePath = GetFilePathFromSaveDialog();

            // 如果用户选择了路径，则继续导出
            if (!string.IsNullOrEmpty(selectedFilePath))
            {
                // 导出 Excel 文件
                bool exportSuccess = ExportExcelFileToEvalBenchmarkPrice(selectedFilePath, data,1);

                if (exportSuccess)
                {
                    MessageBox.Show($"文件已成功导出到：{selectedFilePath}");
                }
                else
                {
                    MessageBox.Show("文件导出失败");
                }
            }
            else
            {
                MessageBox.Show("未选择导出Excel文件");
            }
            return selectedFilePath; // 如果导出成功，返回文件路径
        }

        // 获取保存文件的路径（封装保存对话框）
        public static string GetFilePathFromSaveDialog(string filename= "全部评标基准价")
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog
            {
                Title = "选择要导出的评标基准价文件",
                Filter = "Excel文件|*.xlsx;*.xls|所有文件|*.*",
                FileName = filename, // 默认文件名
                FilterIndex = 1, // 默认选择Excel文件类型
                RestoreDirectory = true // 保存后恢复上次浏览的目录
            };

            DialogResult result = saveFileDialog.ShowDialog();  // 使用 DialogResult 代替 bool? 
            return result == DialogResult.OK ? saveFileDialog.FileName : null;
        }

        // 导出评标基准价到指定路径的辅助函数
        private static bool ExportExcelFileToEvalBenchmarkPrice(string filePath, ObservableCollection<BasePriceEntry> basePriceEntries)
        {
            // 确保EPPlus的LicenseContext被设置为NonCommercial
            ExcelPackage.LicenseContext = OfficeOpenXml.LicenseContext.NonCommercial;

            // 创建一个新的Excel工作簿
            using (var package = new ExcelPackage())
            {
                // 添加一个工作表
                var worksheet = package.Workbook.Worksheets.Add("评标基准价");

                // 设置表头
                worksheet.Cells[1, 1].Value = "B值";
                worksheet.Cells[1, 2].Value = "下浮系数 K(%)";
                worksheet.Cells[1, 3].Value = "下浮率 Δ(%)";
                worksheet.Cells[1, 4].Value = "评标基准价(万元)";

                // 从第二行开始写入数据
                int row = 2;
                foreach (var entry in basePriceEntries)
                {
                    worksheet.Cells[row, 1].Value = entry.BValue; // 下浮系数
                    worksheet.Cells[row, 2].Value = entry.FloatingK; // 下浮系数
                    worksheet.Cells[row, 3].Value = entry.FloatingRate; // 下浮率
                    worksheet.Cells[row, 4].Value = entry.BasePrice; // 评标基准价
                    row++;
                }
                // 保存到文件
                try
                {
                    FileInfo fileInfo = new FileInfo(filePath);
                    package.SaveAs(fileInfo);
                    return true;
                }
                catch (Exception ex)
                {
                    // 处理异常（可选）
                    MessageBox.Show($"导出失败：{ex.Message}");
                    return false;
                }
            }
        }
        public static bool ExportExcelFileToEvalBenchmarkPrice(string filePath, ObservableCollection<BasePriceEntry> basePriceEntries, int test = 1)
        {
            // 确保EPPlus的LicenseContext被设置为NonCommercial
            ExcelPackage.LicenseContext = OfficeOpenXml.LicenseContext.NonCommercial;

            // 创建一个新的Excel工作簿
            using (var package = new ExcelPackage())
            {
                // 添加一个工作表
                var worksheet = package.Workbook.Worksheets.Add("评标基准价");

                // 设置表头
                worksheet.Cells[1, 1].Value = "B值";
                worksheet.Cells[1, 2].Value = "下浮系数 K(%)";
                worksheet.Cells[1, 3].Value = "下浮率 Δ(%)";
                worksheet.Cells[1, 4].Value = "评标基准价(万元)";

                // 填充数据
                int row = 2; // 从第二行开始填充数据
                foreach (var entry in basePriceEntries)
                {
                    worksheet.Cells[row, 1].Value = entry.BValue; // 下浮系数
                    worksheet.Cells[row, 2].Value = entry.FloatingK; // 下浮系数
                    worksheet.Cells[row, 3].Value = entry.FloatingRate; // 下浮率
                    worksheet.Cells[row, 4].Value = entry.BasePrice; // 评标基准价
                    row++;
                }

                // 保存到文件
                try
                {
                    FileInfo fileInfo = new FileInfo(filePath);
                    package.SaveAs(fileInfo);
                    return true;
                }
                catch (Exception ex)
                {
                    // 处理异常（可选）
                    MessageBox.Show($"导出失败：{ex.Message}");
                    return false;
                }
            }
        }


    }

    /// <summary>
    /// BasePriceCalRes04.xaml 的交互逻辑
    /// </summary>
    public partial class BasePriceCalRes04 : Window, INotifyPropertyChanged
    {
        // 静态字段保存唯一实例
        private static BasePriceCalRes04 _instance;
        private ObservableCollection<BasePriceEntry> _BasePriceEntries;//存储计算结果：B、Δ、K和评标基准价
        private ObservableCollection<BidQuote> _BidQuotes;//各个单位的投标报价

        public void GetBidQuotes(ObservableCollection<BidQuote> bidQuotes)//给当前对话框设置各个单位的投标报价
        {
            _BidQuotes = bidQuotes;
        }
        public ObservableCollection<BasePriceEntry> m_BasePriceEntries // 下浮率、下浮系数和评标基准价
        {
            get { return _BasePriceEntries; }
            set
            {
                _BasePriceEntries = value;
                OnPropertyChanged(nameof(m_BasePriceEntries));
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        public void GetBasePriceEntries(List<BasePriceEntry> BasePriceEntries)
        {
            // 将 List 转换为 ObservableCollection
            m_BasePriceEntries = new ObservableCollection<BasePriceEntry>(BasePriceEntries);
        }

        // 私有构造函数，确保只能通过 Instance 获取实例
        private BasePriceCalRes04()
        {
            InitializeComponent();
            this.DataContext = this; // step1: 设置数据绑定的对象
        }

        // 提供对单例实例的访问
        public static BasePriceCalRes04 Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new BasePriceCalRes04();
                }
                return _instance;
            }
        }

        // 上一步
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            // 获取 BidQuotePrice03 的单例实例
            BidQuotePrice03 BQP03 = BidQuotePrice03.Instance;

            // 如果窗口没有显示，则显示它
            if (!BQP03.IsVisible)
            {
                BQP03.Left = this.Left + (this.Width - BQP03.Width) / 2;
                BQP03.Top = this.Top + (this.Height - BQP03.Height) / 2;
                BQP03.Show();
            }

            // 关闭当前窗口
            this.Hide();
        }

        // 下一步 排名数量
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            // 获取 RangeNumDialog05 的单例实例
            RangeNumDialog05 RND05 = RangeNumDialog05.Instance;
            RND05.SetCompanyBidQuotesAndBidPrices(_BidQuotes, _BasePriceEntries);
            // 如果窗口没有显示，则显示它
            if (!RND05.IsVisible)
            {
                RND05.Left = this.Left + (this.Width - RND05.Width) / 2;
                RND05.Top = this.Top + (this.Height - RND05.Height) / 2;
                RND05.Show();
            }

            // 关闭当前窗口
            this.Hide();
        }

        // 导出评标基准价Excel表格
        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            string path=ExcelReader.ExportEvalBenchmarkPrice(m_BasePriceEntries);

        }
        //绘制折线图
        private void Button_Click_3(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("开发中......");
        }
    }
}
